package com.ctg.behavior.calc.impala.transfer.ltv;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.impala.report.ltv.CtLTVMeasureReport;
import com.ctg.behavior.calc.impala.report.ltv.CtLTVReport;
import com.ctg.behavior.calc.utils.CtCalcPropertyUtils;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcPropertyType;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtLTVTransfer implements CtSQLTransfer {

	@Autowired
	private CtLTVMeasureTransfer measureTransfer;

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {

		if (!(calcObject instanceof CtLTVReport)) {
			log.warn("calcObject is not CtLTVReport, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			return "";
		}
		CtLTVReport report = (CtLTVReport) calcObject;
		log.info("report={}", JSON.toJSONString(report));

		StringBuilder impalaSQL = new StringBuilder();
		List<CtLTVMeasureReport> measureReports = report.getMeasureReports();
		
		List<CtCalcPropertyType> byPropertis = new ArrayList<>();
		if(!measureReports.isEmpty()){
			List<String> byFields = measureReports.get(0).getByFields();
			for (String oneField : byFields) {
				CtCalcPropertyType ptype = CtCalcPropertyUtils.getValueType(oneField);
				byPropertis.add(ptype);
			}
		}
		
		impalaSQL.append(" SELECT tpo.calcDate AS calcDate ");
		impalaSQL.append(" , tpo.event AS event ");
		impalaSQL.append(" , tpo.ltv AS ltv ");
		for (CtCalcPropertyType byProperty : byPropertis) {
			String property = byProperty.getProperty();
			impalaSQL.append(" , tpo.").append(property).append(" AS ").append(property);
		}
		impalaSQL.append(" , tpo.total AS total ");
		impalaSQL.append(" FROM ( ");
		
		for (int index = 0; index < measureReports.size(); index++) {
			CtLTVMeasureReport measureReport = measureReports.get(index);
			String measureSQL = measureTransfer.doTransfer(measureReport, sqlParam);
			if (index > 0) {
				impalaSQL.append(" UNION ").append(measureSQL);
			} else {
				impalaSQL.append(measureSQL);
			}
		}
		
		impalaSQL.append(" ) tpo ");
		impalaSQL.append(" ORDER BY tpo.ltv ASC, tpo.calcDate ASC ");

		log.info("reportSQL={}", impalaSQL);

		return impalaSQL.toString();

	}

}
